<template>
	<view>
		<view :style="{ height: navBarHeight + 'px' }" class="custom-nav-bar">
			<!-- <view class="user-avatar" @click="goBack">
				<up-icon class="user-avatar_img" size="20" :bold="true" name="arrow-left"></up-icon>
				<view class="user-avatar_item">
					我创建的
				</view>
			</view> -->
		</view>
		<view class="up-tabs-container" :style="{top:navBarHeight + 'px'}">
			<view class="">
				<view class="">
					会议记录
				</view>
				<view class="gradient-line"></view>
			</view>
			<uni-search-bar v-model="searchValue" bgColor="#fff" radius="15" placeholder="请输入名称" clearButton="auto"
				cancelButton="none" @confirm="search" @clear="clearSearch" />
		</view>
		<view class="page-content" :style="{ marginTop: `calc(${navBarHeight + tabTowHeight - 28}px)` }">
			<scroll-view class="content-main" scroll-y="true" @scrolltolower="onScrollToLower"
				:style="{ height: scrollViewHeight + 'px' }">
				<view class="main-list">
					<view v-for="(value, key) in aiNewTaskList" :key="key">
						<view class="main-box_text">
							<text>{{ strFormatMonth(key) }} {{ getWeekday(key) }}</text>
						</view>
						<view class="">
							<uni-swipe-action>
								<uni-swipe-action-item v-for="item in value" :key="item.taskId"
									:style="item.taskStatus == 2 || item.taskStatus == 3 ? '' : 'pointer-events: none;'"
									:right-options="rightOptions" @click="bindClick($event,item)">
									<view class="" @click="showDetail(item)">
										<view class=""
											style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;">
											<view class="main-box_title">
												{{item.taskName.slice(0, -4)}}
											</view>
											<view v-if="item.taskStatus == 0" class="flex-main"
												style="flex-shrink: 0;padding-left: 15px;">
												<view class="load-box">
													<view class="load-box_line"></view>
												</view>
												<view class="load-title">
													处理中
												</view>
											</view>
											<view v-if="item.taskStatus == 1" class="flex-main"
												style="flex-shrink: 0;padding-left: 15px;">
												<!-- <view class="load-box">
													<view class="load-box_line"></view>
												</view> -->
												<view class="load-title">
													排队中
												</view>
											</view>
											<view class="flex-main" style="flex-shrink: 0;padding-left: 15px;"
												v-if="item.taskStatus == 3">
												<view class="load-title" style="color: red">
													失败
												</view>
											</view>
										</view>
										<view class="line2">{{ item.taskContent}}</view>
									</view>
								</uni-swipe-action-item>
							</uni-swipe-action>
						</view>
					</view>
					<!-- 底部加载状态提示 -->
					<view v-if="aiTaskList.length!=0" class="loading-footer">
						<text v-if="noMore">没有更多了~</text>
						<text v-else-if="loading">加载中...</text>
					</view>
					<view v-else class="loading-footer_home">
						<image src="/static/image/noData.png" mode="aspectFit" style="width: 100%;">
						</image>
					</view>
				</view>
			</scroll-view>
		</view>
		<uni-fab ref="fab" :pattern="pattern" horizontal="right" @fabClick="fabClick" />
		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<view class="dialog-rename">
					<view class="">
						<view class="dialog-rename-title">
							重命名
						</view>
						<view class="dialog-rename-input">
							<input v-model="newRecName" type="text" name="" id="" />
						</view>
					</view>
					<view class="flex-between-mian">
						<view class="dialog-rename_btn" @click="dialogInputClose">取消</view>
						<view class="dialog-rename_btn dialog-rename_btn__left" @click="dialogInputConfirm">保存</view>
					</view>
				</view>
				<!-- <uni-popup-dialog ref="inputClose" mode="input" cancelText="取消" confirmText="保存" title="重命名"
					:value="newRecName" placeholder="请输入内容" @confirm="dialogInputConfirm"
					@close="dialogInputClose"></uni-popup-dialog> -->
			</uni-popup>
		</view>
		<view>
			<uni-popup ref="alertDelDialog" type="dialog">
				<uni-popup-dialog type="info" cancelText="否" confirmText="是" title="删除" content="是否删除当前数据?"
					@confirm="delConfirm" @close="delClose"></uni-popup-dialog>
			</uni-popup>
		</view>
		<up-toast ref="uToastRef"></up-toast>
	</view>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance,
		onMounted,
		onUnmounted,
		reactive,
		watch,
		nextTick
	} from 'vue';
	import {
		onShow,
		onHide,
		onPageScroll,
		onReady
	} from '@dcloudio/uni-app'
	import {
		useAuthStore
	} from '@/store/index.js';
	import {
		listAiTask,
		delAiTask,
		updateAiTask,
		getAiTask
	} from '../../api/index.js';
	import {
		useRecordingStore
	} from '@/store/useRecordingStore';
	import {
		recReq,
		startRecordingWithVisualization,
		stopRecording,
		pauseRecording,
		resumeRecording,
		getRecorder,
		isRecording,
		getWaveView,
		getABufData,
		getRecpowert
	} from '@/utils/globalRecorder';
	import {
		getNewDateArr
	} from '@/utils/list.js'
	import {
		strFormatMonth,
		getWeekday
	} from '@/utils/format.js'
	import {
		getToken,
		saveToken,
		removeToken
	} from '@/utils/auth';

	const navBarHeight = ref(0);
	const userStore = useAuthStore();
	const aiTaskList = ref([])
	const aiNewTaskList = ref([])
	const userId = ref(userStore.userId);
	const isListPageActive = ref(false); // 是否在列表页面
	const recordStore = useRecordingStore();
	const scrollViewHeight = ref(0);
	const tabTowHeight = ref(0)

	const queryParams = reactive({
		pageNum: 1,
		pageSize: 10,
		userId: userStore.userId,
		orderByColumn: 'create_time',
		isAsc: 'desc'
	})
	const total = ref()
	// 新增状态变量
	const loading = ref(false) // 加载中状态
	const noMore = ref(false) // 数据全部加载完成标志
	const pattern = reactive({
		icon: 'mic-filled'
	})
	const searchValue = ref('')
	const rightOptions = reactive([{
		text: '重命名',
		style: {
			backgroundColor: '#007aff',
			color: '#fff',
			height: '100%' // 与 main-box 的高度一致
		}
	}, {
		text: '删除',
		style: {
			backgroundColor: '#dd524d',
			color: '#fff',
			height: '100%' // 与 main-box 的高度一致
		}
	}])
	const inputDialog = ref(null)
	const newRecName = ref('')
	const suffixName = ref('')
	const alertDelDialog = ref(null)
	const changeId = ref(null)
	const uToastRef = ref(null)
	const intervalId = ref(null); // 让 Vue 追踪 intervalId
	const isLoadFirst = ref(false)

	const goBack = () => {}

	const showDetail = (val) => {
		uni.navigateTo({
			url: `/pages/list/detail?taskId=${val.taskId}&taskName=${val.taskName}&taskMindMap=${val.taskMindMap}&taskMindXxcMap=${val.taskMindXxcMap}`
		});
	}

	const deepEqual = (obj1, obj2) => {
		if (obj1 === obj2) return true;

		if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
			return false;
		}

		const keys1 = Object.keys(obj1);
		const keys2 = Object.keys(obj2);

		if (keys1.length !== keys2.length) return false;

		for (let key of keys1) {
			if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
				return false;
			}
		}

		return true;
	}

	/* 表格操作 */
	/** 查询ai任务列表 */
	const getList = async (isRefresh) => {
		queryParams.userId = userStore.userId
		try {
			if (isRefresh) {
				// **仅获取第一页的数据**
				const refreshParams = {
					...queryParams,
					pageNum: 1
				};
				const res = await listAiTask(refreshParams);
				const newData = res.data.rows;

				// **仅更新 taskStatus === 0 的数据**
				aiTaskList.value = aiTaskList.value.map(item => {
					if (item.taskStatus == 0 || item.taskStatus == 1) {
						const updatedItem = newData.find(newItem => newItem.taskId == item.taskId);
						updatedItem ? uni.$emit('refreshHomeList', true) : ''
						return updatedItem ? updatedItem : item; // 只替换有更新的任务
					}
					return item;
				});

				// 重置页码
				// queryParams.pageNum = 1;
				// noMore.value = false;
			} else {
				const res = await listAiTask(queryParams)
				const newData = res.data.rows;
				// 首屏加载
				if (queryParams.pageNum === 1) {
					aiTaskList.value = newData
				}
				// 滚动加载更多
				else {
					aiTaskList.value = [...aiTaskList.value, ...newData]
				}

				// 判断是否还有更多数据
				if (aiTaskList.value?.length >= res.data.total || newData?.length < queryParams.pageSize) {
					noMore.value = true
				}

				// 页码递增（需要放在数据合并之后）
				if (newData?.length > 0) {
					queryParams.pageNum++
				}
			}
			aiNewTaskList.value = getNewDateArr(aiTaskList.value)
		} catch (error) {
			console.error('加载失败:', error)
		} finally {
			// loading.value = false
			// uni.hideLoading()
		}
	};

	// 滚动到底部触发
	const onScrollToLower = () => {
		if (!noMore.value) getList(false)
	}

	// 定义搜索方法，当 @confirm 事件触发时调用
	const search = async (e) => {
		queryParams.taskName = e.value
		await reGetList()
	};

	const clearSearch = async () => {
		delete queryParams.taskName
		await reGetList()
	}

	const bindClick = async (e, item) => {
		changeId.value = item.taskId
		if (e.index == 0) {
			if (item.taskName.includes('.')) {
				let parts = item.taskName.split('.'); // ["example", "com"]
				newRecName.value = parts[0]
				suffixName.value = parts[1]
			} else {
				newRecName.value = item.taskName
				suffixName.value = ''
			}
			await nextTick();
			inputDialog.value.open();
		} else {
			alertDelDialog.value.open()
		}
	}

	const dialogInputClose = () => {
		changeId.value = null
		newRecName.value = '请输入名称'
		suffixName.value = ''
		inputDialog.value.close()
	}

	const dialogInputConfirm = async () => {
		const {
			data
		} = await updateAiTask({
			userId: userStore.userId,
			taskId: changeId.value,
			taskName: newRecName.value + '.' + suffixName.value
		})
		if (data.code == 200) {
			uni.showToast({
				title: '修改成功',
				icon: 'none'
			});
			// 在本地数据中更新任务名称
			aiTaskList.value = aiTaskList.value.map(item => {
				if (item.taskId === changeId.value) {
					return {
						...item,
						taskName: newRecName.value + '.' + suffixName.value
					};
				}
				return item;
			});
			// 更新 aiNewTaskList
			aiNewTaskList.value = getNewDateArr(aiTaskList.value);
			uni.$emit('refreshHomeList', true)
			await dialogInputClose()
		} else {
			uni.showToast({
				title: '修改失败,请重试',
				icon: 'fail',
				icon: 'none'
			})
			inputDialog.value.close()
		}
	}

	const delConfirm = async () => {
		const {
			data
		} = await delAiTask(changeId.value)
		if (data.code == 200) {
			uni.showToast({
				title: '删除成功',
				icon: 'none'
			});
			// 在本地数据中移除任务
			aiTaskList.value = aiTaskList.value.filter(item => item.taskId !== changeId.value);
			// 更新 aiNewTaskList
			aiNewTaskList.value = getNewDateArr(aiTaskList.value);
			uni.$emit('refreshHomeList', true)
			await delClose()
		} else {
			uni.showToast({
				title: '删除失败,请重试',
				icon: 'fail',
				icon: 'none'
			})
			alertDelDialog.value.close()
		}
	}

	const delClose = () => {
		changeId.value = null
		alertDelDialog.value.close()
	}

	const reGetList = () => {
		aiTaskList.value = []
		queryParams.pageNum = 1
		noMore.value = false; // 重置加载状态
		getList(false)
	}

	onMounted(async () => {
		isListPageActive.value = true;
		uni.$emit('stopHomeWatch'); // 通知首页停止监听
		try {
			const res = await uni.getSystemInfo();
			// 获取状态栏高度（刘海高度）
			const statusBarHeight = res.statusBarHeight;
			// 标准导航栏高度，一般为 44px（iOS）或 48px（Android）
			const defaultNavBarHeight = res.platform === 'ios' ? 44 : 48;
			// 计算自定义导航栏的高度
			navBarHeight.value = statusBarHeight + defaultNavBarHeight;
			scrollViewHeight.value = res.windowHeight - navBarHeight.value - tabTowHeight.value;
		} catch (error) {
			console.error('获取设备信息失败:', error);
		}
		if (recordStore.isRecording && !recordStore.isPaused) {
			// 如果录音正在进行中，录音应该继续保持
			// resumeRecording(); // 继续录音
		} else if (recordStore.isPaused) {
			// 如果录音被暂停，保持暂停
			// 不需要恢复录音
		}
		queryParams.pageNum = 1 // 重置页码
		noMore.value = false
		if (getToken()&&!isLoadFirst.value) {
			await reGetList()
		}
		if (recordStore.isRecording) {
			uni.showToast({
				title: '录音继续中，可点击右下角浮层回到录音页',
				icon: 'none'
			})
		}
	});

	const fabClick = () => {
		if (!getToken()) {
			uToastRef.value.show({
				type: 'default',
				message: '请先登录',
				title: '请先登录'
			});
			uni.navigateTo({
				url: '/pages/login'
			})
			return
		}
		uni.navigateTo({
			url: '/subPackages/record/index?type=list'
		})
	}

	// 封装轮询方法
	const startPolling = () => {
		if (!intervalId.value && isListPageActive.value) {
			intervalId.value = setInterval(() => {
				getList(true);
			}, 3000);
		}
	}

	const stopPolling = () => {
		clearInterval(intervalId.value);
		intervalId.value = null;
	}

	// 修改后的 watch
	watch(aiTaskList, (newList) => {
		if (!isListPageActive.value) return;

		if (newList?.some(item => item.taskStatus == "0" || item.taskStatus == "1")) {
			startPolling();
		} else {
			stopPolling();
		}
	}, {
		deep: true
	});

	onShow(async () => {
		isListPageActive.value = true;
		uni.$emit('stopHomeWatch'); // 通知首页停止监听
		uni.$off('refreshList');
		uni.$on('refreshList', (e) => {
			if (e) {
				reGetList()
				// queryParams.pageNum = 1
				// noMore.value = false; // 重置加载状态
				// aiTaskList.value = []
				// getList(false)
			}
		});
		if (uni.getStorageSync('needRefreshList')) {
			reGetList()
			isLoadFirst.value = true
			uni.removeStorageSync('needRefreshList');
		}
		if (aiTaskList.value?.some(item => item.taskStatus == "0" || item.taskStatus == "1")) {
			startPolling();
		}
	});

	// 页面隐藏时移除监听
	onHide(() => {
		isListPageActive.value = false;
		clearInterval(intervalId.value);
		intervalId.value = null;
	});

	onUnmounted(() => {
		isListPageActive.value = false;
		isLoadFirst.value = false
		if (intervalId.value) {
			clearInterval(intervalId.value);
			intervalId.value = null;
		}
	});

	uni.$on('stopListWatch', () => {
		isListPageActive.value = false;
		clearInterval(intervalId.value);
		intervalId.value = null;
	});

	onReady(() => {
		// 获取系统窗口高度
		const systemInfo = uni.getSystemInfoSync()
		nextTick(() => {
			// 获取 tabs 组件高度
			uni.createSelectorQuery()
				.select('.up-tabs-container')
				.boundingClientRect(rect => {
					tabTowHeight.value = rect.height
				})
				.exec()
		})
	})
</script>

<style>
	.custom-nav-bar {
		position: fixed;
		/* 让导航栏固定在顶部 */
		top: 0;
		left: 0;
		width: 100%;
		z-index: 999;
		background: #f5f7fb;
		/* 防止透明导致内容穿透 */
		/* 确保在最上层 */
		/* display: flex;
		align-items: center;
		justify-content: center; */
	}

	.up-tabs-container {
		position: fixed;
		left: 0;
		right: 0;
		background-color: #f5f7fb;
		z-index: 1;
		font-size: 20px;
		padding: 0 20px;
		width: 100%;
		z-index: 999;
		height: unset;
		box-sizing: border-box;
	}

	.gradient-line {
		width: 30%;
		height: 10px;
		/* 线的高度 */
		background: linear-gradient(to right, #2979ff, transparent);
		border-radius: 10px 0 0 10px;
		margin-top: -3%;
	}

	.user-avatar {
		position: absolute;
		left: 15px;
		bottom: 10px;
		overflow: hidden;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: baseline;
	}

	.user-avatar_item {
		margin-left: 2px;
		font-size: 20px;
		font-weight: 700;
	}

	.page-content {
		flex: 1;
	}

	.content-main {
		overflow-y: auto;
	}

	.main-list {
		/* display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 20px 10px; */
		height: 100%;
		padding: 20px;
		/* display: flex;
		flex-wrap: wrap;
		gap: 15px; */
	}

	.main-box {
		width: 100%;
		/* width: calc(50% - 10px); */
		/* 固定宽度计算（减去间隙的一半） */
		min-width: 0;
		/* 防止内容溢出影响布局 */
		border-radius: 15px;
		border: 1px solid #ececec;
		box-sizing: border-box;
		padding: 20px 10px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		/* 添加以下属性确保内容不会撑开盒子 */
		overflow: hidden;
		word-break: break-word;
		/* 长文本自动换行 */
		margin-bottom: 20px;
		/* 控制下方间距 */
	}

	.warning {
		background-color: rgba(230, 162, 60, 0.3);
		pointer-events: none;
	}

	.primary {
		background-color: rgba(64, 158, 255, 0.3);
	}

	.success {
		background-color: rgba(103, 194, 58, 0.3);
	}

	.danger {
		background-color: rgba(250, 53, 52, 0.3);
		pointer-events: none;
	}

	.main-box_title {
		flex: 1;
		display: -webkit-box;
		/* 关键属性 */
		-webkit-box-orient: vertical;
		/* 文字垂直排列 */
		-webkit-line-clamp: 1;
		/* 限制显示两行 */
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 1.5;
		/* 建议设置行高，避免文字重叠 */
		/* height: 3em; */
		/* 两行高度（1.5行高 x 2） */
		font-weight: 600;
		font-size: 18px;
		max-width: 90%;
	}

	.main-box_status {
		/* display: flex;
		flex-direction: row; */
		/* margin-top: 10px; */
		position: absolute;
		right: 0;
	}

	.line2 {
		word-break: break-all;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		font-size: 13px;
		margin-top: 20rpx;
		line-height: 1.5;
		color: #404040;
	}

	.statusBar {
		width: 120rpx;
		line-height: 50rpx;
		text-align: center;
	}

	/* 新增底部加载提示样式 */
	.loading-footer {
		width: 100%;
		flex-basis: 100%;
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 26rpx;
	}

	.flex-main {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.load-box {
		width: 13px;
		height: 13px;
		position: relative;
		border: 2px solid #ececec;
		/* 圆环的粗细和颜色 */
		border-radius: 50%;
		/* 关键：设为圆形 */
		background: transparent;
		/* 背景透明 */
	}

	.load-title {
		color: #000;
		font-size: 13px;
		margin-left: 10px;
	}

	.load-box_line {
		position: absolute;
		width: 100%;
		height: 100%;
		border-radius: 50%;
		border-style: solid;
		border-color: #5c98fb transparent transparent #5c98fb;
		border-width: 2px 2px 0 0;
		animation: animate 1s linear infinite normal;
	}

	@keyframes animate {
		to {
			transform: rotate(1turn);
		}
	}

	.main-box_bottom {
		margin-top: 8px;
	}

	.dialog-rename {
		background: #fff;
		border-radius: 15px;
		padding: 0 20px;
	}

	.dialog-rename-title {
		font-size: 16px;
		font-weight: 500;
		color: #909399;
		padding: 20px;
	}

	.dialog-rename-input {
		width: 50vw;
		padding: 5px 10px;
		border: 1px #eee solid;
		border-radius: 14px;
		font-size: 13px;
		color: #555;
		margin: 0 20px 20px 20px;
	}

	.flex-between-mian {
		display: flex;
		flex-direction: row;
		border-top-color: #f5f5f5;
		border-top-style: solid;
		border-top-width: 1px;
	}

	.dialog-rename_btn {
		display: flex;
		flex: 1;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		height: 45px;
		font-size: 16px;
		color: #333;
	}

	.dialog-rename_btn__left {
		border-left-color: #f0f0f0;
		border-left-style: solid;
		border-left-width: 1px;
	}

	.loading-footer_home {
		width: 100%;
		margin-top: 20px;
	}

	::v-deep .uni-swipe_text--center {
		width: 100%;
		min-width: 0;
		border-radius: 15px;
		border: 1px solid #ececec;
		box-sizing: border-box;
		padding: 20px 10px;
		/* box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); */
		overflow: hidden;
		word-break: break-word;
		background-color: #fff;
	}

	::v-deep .uni-swipe {
		margin-bottom: 20px;
	}

	::v-deep .uni-swipe_button-group>.uni-swipe_button:nth-child(2) {
		border-radius: 0 15px 15px 0;
	}

	::v-deep .uni-searchbar {
		padding: 10px 0 !important;
	}

	::v-deep .uni-searchbar__box {
		border: 1px solid #ececec;
	}
</style>